package com.imooc.network;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/** TCP网络编程 客户端与服务端交互
 * @Date:2021/10/20/21:11
 * @Description:
 */
public class TCPTest03 {

    @Test
    public void client() throws IOException {
        Socket socket = new Socket(InetAddress.getByName("localhost"),9090);
        OutputStream os = socket.getOutputStream();

        FileInputStream fileInputStream = new FileInputStream(new File("中国K线.png")); //本地文件输入流


        byte[] buffer = new byte[2020];
        int len;
        while ((len=fileInputStream.read(buffer)) !=-1){

            os.write(buffer);
        }

        //必须关闭输出
        socket.shutdownOutput();

        //5 接受来着服务器的数据
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        byte[] bytes = new byte[2020];
        int len2;
        while ((len2 =inputStream.read(bytes)) !=-1){

            byteArrayOutputStream.write(bytes);
        }
        System.out.println("byteArrayOutputStream = " + byteArrayOutputStream.toString());

        //关闭通道
        byteArrayOutputStream.close();
        inputStream.close();
        socket.close();
        fileInputStream.close();
    }


    @Test
    public void server() throws IOException {

        //1 接受客户端的数据

        ServerSocket serverSocket = new ServerSocket(9090);
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream(new File("中国K线输出流.png"));

        byte[] bytes = new byte[2024];
        int len;
        while ((len=inputStream.read(bytes) ) !=-1){

            fileOutputStream.write(bytes,0,len);
        }
        System.out.println("图片传输完成");

        //2 服务器给客户端反馈
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("你好，照片已收到".getBytes());

        //关闭通道
        outputStream.close();
        fileOutputStream.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }

}
